// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  // 商品表id
  const {id} = event;
  const {data} = await db.collection('mock_car').where({
    product_id: id,
    _openid: wxContext.OPENID
  }).get()
  let result = null
  if(!data.length) {
    const data = await db.collection('mock_product').field({
      title: true,
      image: true,
      price: true
    }).where({_id: id}).get();
    result = await db.collection('mock_car').add({
      data: {
        ...(data.data[0]),
        product_id: id,
        count: 1,
        _openid: wxContext.OPENID
      }
    })
  } else {
    result = await db.collection('mock_car').doc(data[0]._id).update({
      data: {
        count: _.inc(1)
      }
    })
  }
  return result
}